package com.project.controller;

import com.project.entity.CarGoods;
import com.project.entity.Order;
import com.project.entity.Result;
import com.project.entity.User;
import com.project.service.CarGoodsService;
import com.project.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/carGoods")
public class CarGoodsController {
    @Autowired
    private CarGoodsService carGoodsService;

    @GetMapping("/page/{pageIndex}/{pageItemCount}")
    public Result findPage(@PathVariable Integer pageIndex,@PathVariable Integer pageItemCount) {
        if(pageItemCount == null){
            pageItemCount = 5;
        }
        Result result = new Result();
        result.success("查询成功");
        result.putData("carGoodsList",carGoodsService.findPage(pageIndex, pageItemCount));
        return result;
    }


    @GetMapping("/findAll")
    public Result findAll( HttpServletRequest request) {

        String userName = ((User)request.getSession().getAttribute("loginUser")).getUserName();

        Result result = new Result();
        List<CarGoods> all = carGoodsService.findAll(userName);
        result.success("查询全部成功");
        result.putData("carGoodsList",all);

        return result;
    }


    @PostMapping("save")
    public Result save(CarGoods carGoods, HttpServletRequest request) {
        Result result = new Result();
        try {
            String userName = ((User)request.getSession().getAttribute("loginUser")).getUserName();

            String msg = carGoodsService.save(carGoods,userName);
            result.success(msg);
        }catch (Exception e){
            e.printStackTrace();
            result.error("失败");
        }

        return result;
    }

    @PostMapping("modify/{count}/{shoppingId}")
    public Result updateCount(@PathVariable  Integer count,@PathVariable Integer shoppingId) {
        Result result = new Result();
        try {
            carGoodsService.updateCount(count,shoppingId);
            result.success("成功");
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

    @DeleteMapping("delete/{shoppingId}")
    public Result delete(@PathVariable Integer shoppingId) {
        Result result = new Result();

        try {
            carGoodsService.deleteById(shoppingId);
            result.success("成功");
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }
}
